import goodsItem from "../comm/goodsItem.vue";
import footerTabbar from "../comm/footerTabbar.vue";
import { appAgentConfig } from "utils/wx_app_agent_mixin.js"; // 企业微信侧边栏应用授权
import { scrollMixin } from "../../../utils/mixin";
import BScroll from "better-scroll";
export default {
  name: "",
  //import引入的组件需要注入到对象中才能使用
  components: {
    goodsItem,
    footerTabbar
  },
  mixins: [scrollMixin, appAgentConfig], //加载更多
  data() {
    return {
      chatStrId: "",
      getConfig: { client: "work", type: 17 }, //企业微信公共参数
      active: 2,
      value: "",
      storeScroll: "",
      classifyScroll: "",
      classifyIndex: 0,
      classify: [
        {
          id: "",
          name: "全部"
        }
      ],
      classifyList: [],
      //分页
      isLoadMore: true,
      total_page: 0,
      query: {
        page: 1,
        search: {
          keyword: "",
          category_id: ""
        }
      },
      debounce_timer:0,
      classify_timer:0,
      clientFlag:'',
      footerFlag:true
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    // 错误日志
    debounce() {
      // clearTimeout方法，以便控制连续触发带来的无用调用
      if (this.debounce_timer) {
        clearTimeout(this.debounce_timer); // 先清除之前的延时，并在下面重新开始计算时间
      }
      this.debounce_timer = setTimeout(() => {
        // 800毫秒以后执行方法
        this._initScrollList();
      }, 800); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
    },
    _initScrollList() {
      if (this.classifyList.length > 0) {
        this.storeScroll = new BScroll(this.$refs.handpickList, {
          click: true,
          scrollY: true,
          probeType: 3,
          swipeBounceTime: 500,
          useTransition: false,
          mouseWheel: true
        });
      } else {
        this.storeScroll.refresh();
      }
      let loadMore = document.getElementById("loadMore");
      this.storeScroll.on("scroll", pos => {
        if (loadMore.offsetTop > this.$refs.handpickList.offsetHeight && loadMore.offsetTop + pos.y < this.$refs.handpickList.offsetHeight && this.isLoadMore) {
          this.getMoreData();
          console.log("分类加载更多");
          setTimeout(() => {
            this.storeScroll.refresh();
          }, 800);
        }
      });
      this.$once("hook:beforeDestroy", () => {
        console.log('是否执行');
        window.removeEventListener("scroll", this.storeScroll);
        
      });
    },
    initData() {
      this.classify = [
        {
          id: "",
          name: "全部"
        }
      ];
      this.storeScroll = '';
      this.classifyList = [];
    },
    _initScrollClassify() {
      if (this.classify.length > 0) {
        this.classifyScroll = new BScroll(this.$refs.classifyArr, {
          click: true,
          scrollY: true,
          probeType: 3,
          swipeBounceTime: 500,
          useTransition: false,
          mouseWheel: true
        });
      }
    },
    searchTo() {
      this.$router.push(this.fun.getUrl("courseSearch", {}, {}));
    },
    classifyOnText(index, id,event) {
      if (this.classify_timer) {
        clearTimeout(this.classify_timer); // 先清除之前的延时，并在下面重新开始计算时间
      }
      this.classify_timer = setTimeout(() => {
        // 800毫秒以后执行方法
        this.query.page = 1;
        this.classifyIndex = index;
        this.query.search.category_id = id;
        if (this.storeScroll) {
          this.storeScroll.scrollTo(0, 0);
        }
        this.getCoursesList();
      }, 50); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
      
      
    },
    contactsUid() {
      wx.invoke("getCurExternalChat", {}, res => {
        if (res.err_msg == "getCurExternalChat:ok") {
          this.chatStrId = res.chatId;
          this.getCategory();
          this.getCoursesList();
          window.localStorage.setItem("chat_id", res.chatId);
        } else {
          console.log("wx.getCurExternalChat::res", res);
          //错误处理
        }
      });
    },
    getCategory() {
      //分类
      let query = {};
      if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
        query = { ...this.getConfig, chat_str_id: this.chatStrId };
      }
      $http
        .post("plugin.wechat-video-courses.frontend.controller.manage.courses.get-category", query, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            let categoryList = data.category_list;
            let classify = this.classify;
            this.classify = [...classify, ...categoryList];
            this.$nextTick(() => {
              this._initScrollClassify();
            }, 50);
            // this.classify = data.category_list;
          } else {
            this.$toast("getCategory error", res.msg);
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    getCoursesList() {
      //分类商品
      let query = this.query;
      if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
        this.query = { ...this.getConfig, ...query, chat_str_id: this.chatStrId };
      }
      $http.post("plugin.wechat-video-courses.frontend.controller.manage.courses.index", this.query, "加载中..").then(response => {
        if (response.result == 1) {
          let res = response.data;
          let coursesList = res.courses_list.data;
          this.isLoadMore = true;
          this.total_page = res.courses_list.last_page;
          if (!this.total_page) {
            this.query.page = 0;
          }
          this.classifyList = coursesList;

          this.$nextTick(() => {
            this.debounce();
          }, 50);
        } else {
          this.query.page = this.query.page - 1;
          this.isLoadMore = false;
          this.$dialog.alert({
            message: response.msg
          });
        }
      });
    },
    //获取更多数据
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.query.page >= this.total_page) {
        return;
      } else {
        this.query.page = this.query.page + 1;
        $http.post("plugin.wechat-video-courses.frontend.controller.manage.courses.index", this.query, "加载中").then(
          res => {
            this.isLoadMore = true;
            if (res.result === 1) {
              let coursesList = res.data.courses_list?.data;
              this.classifyList = [...this.classifyList, ...coursesList]; //数组拼接
            } else {
              this.query.page = this.query.page - 1;
              this.isLoadMore = false;
            }
          },
          function(response) {
            console.log("response", response);
            // error callback
          }
        );
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.appjsApiList = ["getCurExternalChat", "getCurExternalContact", "getContext"];
    this.agentConfigUrl = "plugin.wechat-video-courses.frontend.controller.config.index";
    this.clientFlag =  window.localStorage.getItem('client');
    if(this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
      this.footerFlag = false;
      this.appSignSuccess = () => {
        wx.invoke("getContext", {}, res => {
          if (res.err_msg == "getContext:ok") {
            let entry = res.entry; //返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
            console.log("=========获取进入H5页面的入口环境 ====: ", entry);
            if (entry == "group_chat_tools") {
              console.log("group_chat_tools,group_chat_tools");
              this.contactsUid(); //获取群绑定的外部联系人的会员ID,若为空则表示没有绑定外部联系人
            } else {
              wx.invoke("getCurExternalContact", {}, res => {
                console.log("getCurExternalContact:::", res);
                if (res.err_msg == "getCurExternalContact:ok") {
                  console.log("getCurExternalContact:ok ::::::::::::::", res.userId);
                } else {
                  //错误处理
                  this.$toast("获取当前外部联系人失败！");
                }
              });
            }
          } else {
            //错误处理
            console.log("wx.getContext err::", res);
          }
        });
      };
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
    this.query.page = 1;
    if (this.fun.getKey("client") !== "work" || !window.localStorage.getItem("client")) {
      this.initData();
      this.getCategory();
      this.getCoursesList();
    }
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
